package com.study.webapp.jdk8;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ABC1 {

//    public static void main(String[] args) throws InterruptedException {
//
//        //用线程池来实现 ，3个线程加入线程池
//        ExecutorService pool = Executors.newSingleThreadExecutor();
//
//        for (int i = 0; i < 10; i++) {
//            pool.submit(()-> System.out.println("AAAAAA"));
//            pool.submit(()-> System.out.println("BBBBBB"));
//            pool.submit(()-> System.out.println("CCCCCC"));
//        }
//        pool.shutdown();
//
//    }

    private static Lock lock = new ReentrantLock();
    private static int state = 0;

    static class ThreadA extends Thread {
        @Override
        public void run() {
            for(int i = 0; i<10;i++) {
                lock.lock();
                if (state % 3 == 0) {
                    System.out.println("AAA");
                    state++;
                }
                lock.unlock();
            }
        }
    }

    static class ThreadB extends Thread {
        @Override
        public void run() {
            for(int i = 0; i<10;i++) {
                lock.lock();
                if (state % 3 == 1) {
                    System.out.println("BBB");
                    state++;
                }
                lock.unlock();
            }
        }
    }

    static class ThreadC extends Thread {
        @Override
        public void run() {
            for(int i = 0; i<10;i++) {
                lock.lock();
                if (state % 3 == 2) {
                    System.out.println("CCC");
                    state++;
                }
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        new ThreadA().start();
        new ThreadB().start();
        new ThreadC().start();
    }
}
